#pragma once

#include<thread>
#include<vector>
#include<queue>
#include<mutex>
#include <condition_variable>
#include<functional>
#include<unistd.h>
#include<iostream>

template<typename T>
class ThreadPool
{
    void threadRoutine()//线程的回调函数
    {
        while(1)
        {
            T task;
            {
                std::unique_lock<std::mutex> uni_mutex(_mutex);
                while(_q.empty())
                {
                    _cond.wait(uni_mutex);
                }
                task=_q.front();
                _q.pop();
            }
            
            //处理任务...
            task();
            task.debug();
        }
    }
public:
    ThreadPool(int thread_num=5):_thread_num(thread_num)
    {
        //创建出一批线程
        for(int i=0;i<thread_num;i++)
        {
            //_threads.push_back(std::thread(&ThreadPool<T>::threadRoutine,this));//构造，移动
            _threads.emplace_back(&ThreadPool<T>::threadRoutine,this);//构造
        }
    }
    void push(const T& task)//提交任务
    {
        std::unique_lock<std::mutex> uni_mutex(_mutex);
        _q.push(task);
        _cond.notify_one();
    }
private:
    std::vector<std::thread> _threads;
    std::queue<T> _q;//任务队列
    std::mutex _mutex;
    std::condition_variable _cond;
    int _thread_num;//线程数
};